package com.security.door.controller.deviceManage;

import com.github.pagehelper.PageInfo;
import com.security.door.core.wrapper.WrapMapper;
import com.security.door.core.wrapper.Wrapper;
import com.security.door.enums.EnumParamsType;
import com.security.door.model.domain.*;
import com.security.door.model.dto.devDeviceinfoDto;
import com.security.door.model.vo.deviceInfoVo;
import com.security.door.service.IcrAreaDeviceService;
import com.security.door.service.IdevDeviceinfoService;
import com.security.door.service.IdevDeviceparamService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@Api(value = "WEB - devDeviceinfoController", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class devDeviceinfoController {

    @Autowired
    HttpSession session;
    @Autowired
    HttpServletRequest httpServletRequest;
    @Autowired
    IdevDeviceinfoService idevDeviceinfoService;
    @Autowired
    IcrAreaDeviceService icrAreaDeviceService;
    @Autowired
    IdevDeviceparamService idevDeviceparamService;

    @PostMapping("/device/queryListWithPage")
    @ApiOperation(value = "分页查询所有信息", notes = "分页查询所有信息")
    public Wrapper listAll() {
        devDeviceinfoDto entityDto = new devDeviceinfoDto();
        entityDto.setPageIndex(1);
        entityDto.setPageSize(Integer.MAX_VALUE);
        var list = idevDeviceinfoService.queryListWithPage(entityDto);
        return WrapMapper.ok(list.getList());
    }

    @GetMapping(value = "/device/selectTree")
    @ApiOperation(value = "查询设备树", notes = "查询设备树")
    public Wrapper selectTreeVo() {
        devDeviceinfoDto entityDto = new devDeviceinfoDto();
        entityDto.setPageIndex(1);
        entityDto.setPageSize(Integer.MAX_VALUE);
        PageInfo<deviceInfoVo> treeData = idevDeviceinfoService.queryListWithPage(entityDto);
        var list = getTree(treeData.getList(), null);
        return WrapMapper.ok(list);
    }

    private List<deviceInfoVo> getTree(List<deviceInfoVo> list, String parentId) {
        List<deviceInfoVo> listChildrens = null;
        if (parentId == null) {
            listChildrens = list.stream().filter(x -> x.getParentid() == parentId).collect(Collectors.toList());
        } else {
            list.removeIf(x -> x.getParentid() == null);
            listChildrens = list.stream().filter(x -> x.getParentid().equals(parentId)).collect(Collectors.toList());
        }
        List<deviceInfoVo> listVo = new ArrayList<deviceInfoVo>();
        for (var children : listChildrens) {
            children.setId(children.getDevicecode());
            children.setLabel(children.getDevicename());
            var tempList = getTree(list, children.getDevicecode());
            if (tempList.size() > 0)
                children.setChildren(tempList);
            listVo.add(children);
        }
        return listVo;
    }

    @GetMapping("/device/selectByAreaCode/{areaCode}")
    @ApiOperation(value = "分页查询所有信息", notes = "分页查询所有信息")
    public Wrapper selectByAreaCode(@PathVariable("areaCode") String areaCode) {
        //var list = idevDeviceinfoService.selectByAreaCode(areaCode);
        //return WrapMapper.ok(list);
        return null;
    }

    @PostMapping("/device/add")
    @ApiOperation(value = "新增设置", notes = "新增设置")
    public Wrapper insertDevDeviceinfo(@RequestBody devDeviceinfo entity) {
        if ("".equals(entity.getGuid()) || null == entity.getGuid()) {
            if (idevDeviceinfoService.hasExists(entity.getDevicecode()))
                return WrapMapper.error("设备SN已经存在");
            entity.setGuid(UUID.randomUUID().toString());
//            entity.setCreator(user.getRealname());
            entity.setCreatetime(new Date());
            idevDeviceinfoService.save(entity);
        } else {
            idevDeviceinfoService.update(entity);
        }
        return WrapMapper.ok("操作成功");
    }

    @GetMapping(value = "/device/del/{deviceCode}")
    public Wrapper deleteDevDeviceinfo(@PathVariable("deviceCode") String deviceCode) {

        /********************删除设备***********************/
        idevDeviceinfoService.deleteByCode(deviceCode);
        /********************删除设备功能点权限***********************/
//                idevActiveaccessService.deleteBySn(Sn);
        /********************删除设备授权***********************/
//                idevDeviceaccessService.deleteBySn(Sn);
        /********************删除设备参数信息***********************/
//                idevDeviceparamService.deleteBySn(Sn);
        return WrapMapper.ok("操作成功");
    }

    @PostMapping("/device/selectTreeByAreaCode/{areaCode}")
    @ApiOperation(value = "根据区域查询设备树", notes = "根据区域查询设备树")
    public Wrapper selectTreeByAreaCode(@PathVariable("areaCode") String areaCode) {
        devDeviceinfoDto entityDto = new devDeviceinfoDto();
        entityDto.setPageIndex(1);
        entityDto.setPageSize(Integer.MAX_VALUE);
        var list = idevDeviceinfoService.selectTreeByAreaCode(areaCode);
        return WrapMapper.ok(list);
    }

    @PostMapping("/device/pullDevice")
    @ApiOperation(value = "根据区域查询设备树", notes = "根据区域查询设备树")
    public Wrapper pullDevice(@RequestBody devDeviceinfoDto entity) {
        devDeviceinfo tempDevice = null;
        if (idevDeviceinfoService.hasExists(entity.getDevicecode())) {
            tempDevice = idevDeviceinfoService.selectByCode(entity.getDevicecode());
            tempDevice.setDevicename(entity.getDevicename());
            tempDevice.setDevicetypecode(entity.getDevicetypecode());
            idevDeviceinfoService.update(tempDevice);
            idevDeviceparamService.deleteByDeviceCode(entity.getDevicecode(), EnumParamsType.AreaDev.getKey());
        } else {
            //保存设备信息
            tempDevice = new devDeviceinfo();
            tempDevice.setDevicename(entity.getDevicename());
            tempDevice.setDevicecode(entity.getDevicecode());
            tempDevice.setDevicetypecode(entity.getDevicetypecode());
            idevDeviceinfoService.save(tempDevice);
        }
        //保存设备参数
        List<devDeviceparam> listParams = new LinkedList<>();
        for (String key : entity.getDeviceParam().keySet()) {
            String value = entity.getDeviceParam().get(key);
            devDeviceparam temp = new devDeviceparam();
            temp.setDevicecode(entity.getDevicecode());
            temp.setDisplaykey(key);
            temp.setDisplayvalue(value);
            temp.setActivecode(EnumParamsType.AreaDev.getKey());
            temp.setGuid(UUID.randomUUID().toString());
            temp.setCreatetime(new Date());
            listParams.add(temp);
        }
        idevDeviceparamService.batchSave(listParams);
        //保存设备-区域关系
        crAreaDevice m_crAreaDevice = new crAreaDevice();
        m_crAreaDevice.setDevicecode(entity.getDevicecode());
        m_crAreaDevice.setAreacode(entity.getAreacode());
        if (!icrAreaDeviceService.hasExists(m_crAreaDevice)) {
            m_crAreaDevice.setGuid(UUID.randomUUID().toString());
            m_crAreaDevice.setCreatetime(new Date());
            icrAreaDeviceService.save(m_crAreaDevice);
        }
        return WrapMapper.ok("操作成功");
    }
}
